<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :minHeight="500"
    :width="1000"
  >
    <BasicTable @register="registerTable">
      <template #toolbar>
        <!-- Excel导出 -->
        <a-button
          type="primary"
          @click="exportExcel"
          v-show="showExport == 'fromFolder'"
          preIcon="ion:download-outline"
          >{{ t('common.export') }}</a-button
        >
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import {
    GetFolderPermissions,
    GetFileTypePermissions,
    ExportPermissionsToExcel,
  } from '/@/api/demo/document';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  const { t } = useI18n();

  const showExport = ref<any>('');
  const acceptData = ref<any>(null);
  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    acceptData.value = data;
    showExport.value = data.type;
    // 分支判断 目录 type为fromFolder， 文档类型type为fromFileType
    function fetchPermissions(type, selectData, userSelectData) {
      if (type === 'fromFolder') {
        return GetFolderPermissions(selectData, userSelectData);
      } else if (type === 'fromFileType') {
        return GetFileTypePermissions(selectData, userSelectData);
      }
      return Promise.reject('Unknown type');
    }

    function updateTableData(response) {
      setColumns(response.TotalTitle);
      setTableData(
        response.TotalPower.permissions ? response.TotalPower.permissions : response.TotalPower,
      );
    }

    if (data.type === 'fromFolder' || data.type === 'fromFileType') {
      const selectData = data.type === 'fromFolder' ? data.direSelectData : data.typeSelectData;
      fetchPermissions(data.type, selectData, data.userSelectData).then(updateTableData);
    }
  });

  // 目录权限导出
  const exportExcel = async () => {
    await ExportPermissionsToExcel(
      '目录权限显示.xlsx',
      acceptData.value.direSelectData,
      acceptData.value.userSelectData,
    );
    createMessage.success(t('common.downLoadSuccess'));
  };

  // 提交
  function handleSubmit() {
    closeModal();
  }

  // 取消
  function handleCancel() {
    closeModal();
  }

  // 表格初始化
  const [registerTable, { reload, setColumns, setTableData }] = useTable({
    bordered: true,
    useSearchForm: false,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: false }, // 表格设置工具配置
    pagination: false,
    maxHeight: 400,
    striped: false,
    isTreeTable: true,
    childrenColumnName: 'permissions',
  });
</script>

<style scoped></style>
